package com.itheima.intercetpor;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@RestController
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("=============" + request.getRequestURI());
        //1.通过request获取指定请求头:token
        String jwt = request.getHeader("token");
        try {
            //2.调用JwtUtils的方法进行解析
            Map<String, Object> map = JwtUtils.parseJwt(jwt);
            log.info("jwt校验通过:{}", jwt);
            //3.解析成功,放行执行Controller方法
            return true;
        } catch (Exception e) {
            //4.解析失败,拦截代码终止
            log.error("jwt校验失败:{}", jwt);
            //5.设置响应状态码,403是权限不足,401是未登录(全是前端的问题),5开头表示服务器错误
            response.setStatus(401);
            return false;
        }
    }
}
